package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.List;

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;
    @Autowired
    private JedisPool jedisPool;
    @Override
    public void add(Address address) {
        addressDao.add(address);
        jedisPool.getResource().sadd(RedisConstant.ADDRESS_PIC_DB_RESOURCES, address.getImg());
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Address> page = addressDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Address findById(Integer id) {
        return addressDao.findById(id);
    }

    @Override
    public void edit(Address address) {
        addressDao.edit(address);
        //redis缓存图片
        jedisPool.getResource().sadd(RedisConstant.ADDRESS_PIC_DB_RESOURCES, address.getImg());
    }

    @Override
    public void delete(Integer id) {
        long count = addressDao.findByIdFromOrder(id);
        if(count>0){
            throw new RuntimeException("当前地址被引用，不能删除");
        }else {
            addressDao.delete(id);
        }

    }

    @Override
    public List<Address> findAll() {
        return addressDao.findAll();
    }

    @Override
    public Address findByName(String addressName) {
        return addressDao.findByName(addressName);
    }
}
